package com.example.abc.amqp;

import com.example.abc.util.JsonUtil;
import com.example.abc.websocket.OnlineUsers;
import com.example.abc.websocket.msg.LogoutMsg;
import com.example.abc.websocket.msg.WsBaseMessage;
import com.example.abc.websocket.msg.WsMsgType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * Created by Peter on 2018/5/8.
 * MqMsg logout 接收器
 */
@Component
@RabbitListener(queues = "logout")
public class MqMsgReceiver {
    private static final Logger logger = LoggerFactory.getLogger(MqMsgReceiver.class);

    @RabbitHandler
    public void process(LogoutMsg msg) {
        logger.info("MQ Receiver : " + msg);
        WebSocketSession session = OnlineUsers.getUser(msg.getTo());
        try {
            if (session != null) {
                WsBaseMessage baseMessage=new WsBaseMessage();
                baseMessage.setData(msg);
                baseMessage.setType(WsMsgType.logout.name());
                TextMessage textMessage = new TextMessage(JsonUtil.toJson(baseMessage));
                session.sendMessage(textMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
